package qnb.service.impl;

import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import qnb._common.easyui.Tree;
import qnb.dao.SysPowerStudentMapper;
import qnb.dao.SysPowerTeacherMapper;
import qnb.dao.SysRoleMapper;
import qnb.entity.*;
import qnb.service.SysRoleService;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author huangxin
 * @date 2019/5/22-16:05
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysPowerTeacherMapper sysPowerTeacherMapper;

    @Autowired
    private SysPowerStudentMapper sysPowerStudentMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<SysRole> getAllRole() {
        List<SysRole> sysRoleList = sysRoleMapper.selectAll();
        List<SysRole> allRole = getAllRole(0, sysRoleList);
        return allRole;
    }

    /**
     * 更新或新增角色
     *
     * @param sysRoleList
     * @return
     */
    @Override
    public int update(List<SysRole> sysRoleList) {
        updateOrInsert(sysRoleList, 0);
        return 1;
    }

    @Override
    public int delete(Integer id) {
        return sysRoleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 更新角色权限
     *
     * @param id
     * @param ids
     * @return
     */
    @Override
    public int updateRolePowersById(Integer id, List<Integer> ids) {
        SysRole sysRole = new SysRole();
        sysRole.setSysRoleId(id);
        //拼接权限
        String powersStr = ids.stream().map(String::valueOf).collect(Collectors.joining(","));

        sysRole.setSysRolePowers(powersStr);

        return sysRoleMapper.updateByPrimaryKeySelective(sysRole);
    }



    /**
     * 查询所有角色
     * @return
     */
    private List<Tree> getAllRoleToTree(Integer level) {
        List<SysRole> sysRoleList =null;
        if (level == null) {
            sysRoleList = sysRoleMapper.selectAll();
        }else{
            SysRoleExample example = new SysRoleExample();
            example.createCriteria().andSysRoleLevelLessThanOrEqualTo(level);
            sysRoleList = sysRoleMapper.selectByExample(example);
        }

        List<SysRole> collect = sysRoleList.stream().sorted(Comparator.comparing(SysRole::getSysRoleId)).collect(Collectors.toList());
        Integer pid = CollectionUtils.isEmpty(collect) ? 0 : collect.get(0).getSysRolePid();
        return getAllRoleToTree(pid, sysRoleList);
    }

    /**
     * 根据老师id查询角色
     *
     * @param id
     * @return
     */
    @Override
    public List<Tree> getRoleByTeacherId(String id) {
        if ("0".equals(id)) {
            return getAllRoleToTree(1);
        }

        SysPowerTeacher sysPowerTeacher = sysPowerTeacherMapper.selectByPrimaryKey(id);
        //获取所有角色转成tree
        List<Tree> treeList = getAllRoleToTree(1);

        if (sysPowerTeacher != null) {
            //如果存在权限
            String sysRolePowers = sysPowerTeacher.getSysRole();
            if (StringUtils.isNotBlank(sysRolePowers)) {
                List<Integer> idList = Arrays.stream(StringUtils.split(sysRolePowers, ",")).map(Integer::parseInt).collect(Collectors.toList());
                setCheck(treeList, idList);
            }
        }
        return treeList;
    }

    /**
     * 根据学生id查询角色
     * @param id
     * @return
     */
    @Override
    public List<Tree> getRoleByStudentId(String id) {
        if ("0".equals(id)) {
            return getAllRoleToTree(0);
        }

        SysPowerStudent sysPowerStudent = sysPowerStudentMapper.selectByPrimaryKey(id);
        //获取所有角色转成tree
        List<Tree> treeList = getAllRoleToTree(0);

        if (sysPowerStudent != null) {
            //如果存在权限
            String sysRolePowers = sysPowerStudent.getSysRole();
            if (StringUtils.isNotBlank(sysRolePowers)) {
                List<Integer> idList = Arrays.stream(StringUtils.split(sysRolePowers, ",")).map(Integer::parseInt).collect(Collectors.toList());
                setCheck(treeList, idList);
            }
        }
        return treeList;
    }

    /**
     * 更新老师角色
     *
     * @param id
     * @param ids
     * @return
     */
    @Override
    public int updateTeacherRole(String id, List<Integer> ids) {
        SysPowerTeacher sysPowerTeacher = sysPowerTeacherMapper.selectByPrimaryKey(id);
        String idsStr = ids.stream().map(String::valueOf).collect(Collectors.joining(","));
        if (sysPowerTeacher != null) {
            //如果存在
            //更新
            sysPowerTeacher.setSysRole(idsStr);
            return sysPowerTeacherMapper.updateByPrimaryKeySelective(sysPowerTeacher);
        } else {
            //新增
            sysPowerTeacher = new SysPowerTeacher();
            sysPowerTeacher.setTeacherId(id);
            sysPowerTeacher.setSysRole(idsStr);
            return sysPowerTeacherMapper.insertSelective(sysPowerTeacher);
        }

    }

    /**
     * 更新学生角色
     * @param id
     * @param ids
     * @return
     */
    @Override
    public int updateStudentRole(String id, List<Integer> ids) {
        SysPowerStudent sysPowerStudent = sysPowerStudentMapper.selectByPrimaryKey(id);

        String idsStr = ids.stream().map(String::valueOf).collect(Collectors.joining(","));
        if (sysPowerStudent != null) {
            //如果存在
            //更新
            sysPowerStudent.setSysRole(idsStr);
            return sysPowerStudentMapper.updateByPrimaryKeySelective(sysPowerStudent);
        } else {
            //新增
            sysPowerStudent = new SysPowerStudent();
            sysPowerStudent.setStudentId(id);
            sysPowerStudent.setSysRole(idsStr);
            return sysPowerStudentMapper.insertSelective(sysPowerStudent);
        }
    }

    public void setCheck(List<Tree> treeList, List<Integer> idList) {
        treeList.forEach(tree -> {
            if (idList.contains(tree.getId())) {
                tree.setChecked(true);
            }
            if (!CollectionUtils.isEmpty(tree.getChildren())) {
                setCheck(tree.getChildren(), idList);
            }
        });
    }

    public List<Tree> getAllRoleToTree(Integer pid, List<SysRole> sysRoleList) {
        List<Tree> treeList = sysRoleList.stream().filter(s -> pid.equals(s.getSysRolePid()))
                .map(this::toTree).collect(Collectors.toList());

        //是否为空
        if (!CollectionUtils.isEmpty(treeList)) {
            //设置子节点
            for (Tree tree : treeList) {
                tree.setChildren(getAllRoleToTree(tree.getId(), sysRoleList));
            }
            return treeList;
        }
        return null;
    }

    public Tree toTree(SysRole s) {
        return new Tree(s.getSysRoleId(), s.getSysName());
    }


    /**
     * 更新或添加角色
     *
     * @param sysRoleList
     * @param pid
     */
    public void updateOrInsert(List<SysRole> sysRoleList, int pid) {
        for (SysRole sysRole : sysRoleList) {
            //如果pid小于零,则为临时id,设置其pid
            if (sysRole.getSysRolePid() == null || sysRole.getSysRolePid() < 0) {
                sysRole.setSysRolePid(pid);
            }
            //小于0则为新增
            if (sysRole.getSysRoleId() < 0) {
                //id为自增
                sysRole.setSysRoleId(null);
                //新增时间
                sysRole.setSysRoleTime(new Date());
                sysRole.setSysRolePowers(null);
                sysRoleMapper.insertSelective(sysRole);
            } else {
                sysRole.setSysRoleTime(null);
                sysRole.setSysRolePowers(null);
                sysRoleMapper.updateByPrimaryKeySelective(sysRole);
            }
            //如果还有子角色
            if (!CollectionUtils.isEmpty(sysRole.getChildren())) {
                updateOrInsert(sysRole.getChildren(), sysRole.getSysRoleId());
            }
        }
    }

    /**
     * 递归设置角色
     *
     * @param id
     * @param sysRoleList
     * @return
     */
    public List<SysRole> getAllRole(Integer id, List<SysRole> sysRoleList) {
        //过滤
        List<SysRole> collect = sysRoleList.stream()
                .filter(s -> id.equals(s.getSysRolePid())).collect(Collectors.toList());
        //是否为空
        if (!CollectionUtils.isEmpty(collect)) {
            for (SysRole sysRole : collect) {
                sysRole.setChildren(getAllRole(sysRole.getSysRoleId(), sysRoleList));
            }
            return collect;
        }
        return null;
    }


}
